var x;
var y;
var deltaX = 0;
var deltaY = 0;
var mouseDown = false;
var velocityX = 0;
var velocityY = 0;
var similarityArray;
var gamePicturesArray;
var referenceGame;
var centralGameArray;
var gameCoordinateArray = new Array();
var gameId = $("input[name=game_id]").val();
var addDropShadowUrl = $("input[name=addDropShadowUrl]").val();

var pannelIsBeingDisplayed = false;
    

$(document).ready(function() {
    
    $("#map").css('height', window.innerHeight - 46);
    function findPos(el) {
	var x = y = 0;
	if(el.offsetParent) {
		x = el.offsetLeft;
		y = el.offsetTop;
		while(el = el.offsetParent) {
			x += el.offsetLeft;
			y += el.offsetTop;
		}
	}
	return {'x':x, 'y':y};
    }

    var mapWidth = $("#map").width();
    var mapHeight = $("#map").height();
    var draggableMapWidth = $("#draggable-map").width();
    var draggableMapHeight = $("#draggable-map").height();
    
    // we center the draggable-map inside the "frame"
    $("#draggable-map").css('left', '-=' + ((draggableMapWidth - mapWidth) / 2));
    $("#draggable-map").css('top', '-=' + ((draggableMapHeight - mapHeight) / 2));
    
    $("#map").mousedown(function(event) {
        
        // we reinitialize the velocity in order to not
        // wrong the momentum effect if there is no need
        // to
        velocityX = 0;
        velocityY = 0;
        
        // we stock current x and y
        x = event.screenX;
        y = event.screenY;
        
        // if set to true, then the drag effect happens when we move
        // the mouse
        mouseDown = true;
        // if we already were dragging around, then this line stop
        // the animation
        $("#draggable-map").stop();
    });
    
    $("body").mouseup(function(event) {

            // if the mouse is down and the velocity is strong enough to enhance momentum
            // effect...
            if(mouseDown && (Math.abs(velocityX) > 1 || Math.abs(velocityY) > 1)) {
    //            $("#debug-message").html("velocityX : "+velocityX+ "<br>velocityY : "+velocityY);
                $("#draggable-map").animate({'left': '+=' + (20 * velocityX), 'top': '+=' + (20 * velocityY)}, 700, 'easeOutCirc');
            }
            mouseDown = false;

            var ev = event;
                var pos = findPos(document.getElementById('draggable-map'));
                var diffx = ev.clientX - pos.x;
                var diffy = ev.clientY - pos.y;

                var g;

                for(var i in gameCoordinateArray) {
                    g = gameCoordinateArray[i];

    //                alert("diffx ("+diffx+") >= g.newMinX ("+g.newMinX+") ? " +(diffx >= g.newMinX) + "\n" +
    //                  "diffx ("+diffx+") <= g.newMaxX ("+g.newMaxX+") ? " +(diffx <= g.newMaxX) + "\n" +
    //                  "diffy ("+diffy+") >= g.newMinY ("+g.newMinY+") ? " +(diffy >= g.newMinY) + "\n" +
    //                  "diffy ("+diffy+") <= g.newMaxY ("+g.newMaxY+") ? " +(diffy <= g.newMaxY)
    //                );

                    if(diffx >= g.newMinX &&
                        diffx <= g.newMaxX &&
                        diffy >= g.newMinY &&
                        diffy <= g.newMaxY && !($(event.target).is('.customScrollBox')) && !($(event.target).parents().is('.customScrollBox'))) {
                        // todo...

                        var displayGameUrl = $("input[name=displayGameUrl]").val();

                        if (!pannelIsBeingDisplayed) {
                            pannelIsBeingDisplayed = true;
                            $("#pannels").load(displayGameUrl+'/'+g.gameID, function(){
                                // $("#mcs_container").mCustomScrollbar("vertical",0,"linear",1.1, "auto","yes","yes",20);
                                $("#mcs_container").animate({'width': '25%'}, 400, 'easeOutBack', function() {
                                    $("#mcs_container .customScrollBox").fadeToggle();
                                    $("#mcs_container").mCustomScrollbar("vertical",0,"linear",1.25, "auto","yes","yes",1);
                                    $("#closePannelLink").fadeToggle();

                                    $("#showMediaPannelLink").fadeToggle();
                                    pannelIsBeingDisplayed = false;
                                });


                            });
                        }    

                        break;
                    }      
                }
            }       
        );
    
    $("body").mousemove(function(event) {
        if(mouseDown) {
            // we stock the velocity in order to adapt the
            // momentum effect
            velocityX = event.screenX - x;
            velocityY = event.screenY - y;
            // if referential coordinates did not have been initialized
            if(x == null && y == null) {
                x = event.screenX;
                y = event.screenY;
            } else {
                // if the mouse x has changed, we refresh the position
                // of the draggable-map
                if(x != event.screenX) {
                    deltaX = $("#draggable-map").css('left');
                    $("#draggable-map").css('left', '+=' + (event.screenX - x));
                }

                // same as above but for y
                if(y != event.screenX) {
                    deltaY = $("#draggable-map").css('left');
                    $("#draggable-map").css('top', '+=' + (event.screenY - y));
                }

//                $("#debug-message").text('deltaX : ' + deltaX + ' deltaY : ' + deltaY);

                // refreshing the referential coordinates
                x = event.screenX;
                y = event.screenY;
            }
        }
    });
});

/** 
 * canvas 
 */
var i, j;
var criteriaArray = new Array('universe', 'gameplay', 'soundtrack', 'graphics');
var percentageScale = 70;
var centralGameMatrice = new Array();


function draw(criteriaCount, gameImagesArray, similarityArray, gameMatrice) {
    
	centralGameMatrice = new Array();
	gameCoordinateArray = new Array();
	var gameId = $("input[name=game_id]").val();
//    var stage = new Kinetic.Stage({
//      container: "draggable-map",
//      width: 7800,
//      height: 7800
//    });
//    
//    var layer = new Kinetic.Layer();
//    
//    var canvas = layer.getCanvas();
//    console.dir(canvas);
    var canvas = document.getElementById('draggable-map');
    var ctx = canvas.getContext('2d');
    
    // ctx.fillStyle = "rgb(0,0,0)";
    
    
    var degreePerAxis = 360 / criteriaCount;
    var currentDegree = 0;
    // center circle outline
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2, 201, 0, Math.PI*2, true); 
    ctx.closePath();
    ctx.fillStyle = "rgba(255,255,255,0.4)";
    ctx.fill();
    
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2, 200, 0, Math.PI*2, true); 
    ctx.closePath();
    ctx.fillStyle = "rgb(204,204,204)";
    ctx.fill();
    
    // ctx.strokeStyle = "rgba(255,255,255,0.4)";
    // ctx.beginPath();
    // ctx.arc(canvas.width / 2, canvas.height / 2, 199, 0, Math.PI*2, true); 
    // ctx.closePath();
    // ctx.stroke();
    // ctx.fillStyle = "rgb(217,217,217)";
    // ctx.fill();
    // axis outline
    for(; currentDegree < 360 ; currentDegree += degreePerAxis) {
	
        ctx.lineWidth = 13;
        ctx.strokeStyle = "rgba(255,255,255,0.4)";
        
        ctx.beginPath();
        ctx.save();
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate(- currentDegree * Math.PI / 180);
        ctx.translate(- (canvas.width / 2), - (canvas.height / 2));
        ctx.moveTo(canvas.width / 2, canvas.height / 2);
        ctx.lineTo(canvas.width + 500, canvas.height / 2);
        ctx.stroke();
        ctx.restore();
        
        ctx.lineWidth = 11;
        ctx.strokeStyle = "rgb(204,204,204)";
        
        ctx.beginPath();
        ctx.save();
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate(- currentDegree * Math.PI / 180);
        ctx.translate(- (canvas.width / 2), - (canvas.height / 2));
        ctx.moveTo(canvas.width / 2, canvas.height / 2);
        ctx.lineTo(canvas.width + 500, canvas.height / 2);
        ctx.stroke();
        ctx.restore();
        
        ctx.lineWidth = 9;
        ctx.strokeStyle = "rgb(217,217,217)";
        
        ctx.beginPath();
        ctx.save();
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate(- currentDegree * Math.PI / 180);
        ctx.translate(- (canvas.width / 2), - (canvas.height / 2));
        ctx.moveTo(canvas.width / 2, canvas.height / 2);
        ctx.lineTo(canvas.width + 500, canvas.height / 2);
        ctx.stroke();
        ctx.restore();
    }
    
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height / 2, 199, 0, Math.PI*2, true); 
    ctx.closePath();
    ctx.fillStyle = "rgb(217,217,217)";
    ctx.fill();
    
    ctx.strokeStyle = "rgb(204,204,204)";
    ctx.lineWidth = 2;
    
    var centralCircleIndexArray = new Array();
    
    for(var a = 75 ; a < 175 ; a += 50) {
        centralGameMatrice[a] = new Array();
        
        for(b = 0 ; b < (a / 10) ; b++) {
            centralGameMatrice[a][b] = null;
        }
        centralCircleIndexArray.push(a);
    }
    
    var centralCircleIndex = centralCircleIndexArray[0];
    var currentCentralCircleLength;
    var currentIndexInCurrentCentralCircle;
    var availableIndexInCurrentCircle;
    var centralGameSpace;
    var destWidth = 32; // new image width
    var destHeight = 32; // new image height
    var sinus;
    var cosinus;
    var oldMinX;
    var oldMinY;
    var oldMaxX;
    var oldMaxY;
    var newMinX;
    var newMinY;
    var newMaxX;
    var newMaxY;
    var newGameCoordinate;
    
    for(var game in centralGameArray) {	
        
        currentCentralCircleLength = centralGameMatrice[centralCircleIndex].length;
        
        availableIndexInCurrentCircle = new Array();
        
        for(var places in centralGameMatrice[centralCircleIndex]) {
            
            if(centralGameMatrice[centralCircleIndex][places] == null) {
                availableIndexInCurrentCircle.push(places);
            }
        }
        
        currentIndexInCurrentCentralCircle = availableIndexInCurrentCircle[Math.ceil(Math.random() * (availableIndexInCurrentCircle.length - 1))];
        
        
        if(centralGameMatrice[centralCircleIndex][currentIndexInCurrentCentralCircle] == null) {
            
            centralGameMatrice[centralCircleIndex][currentIndexInCurrentCentralCircle] = true;
                
            // save the context
            ctx.save();
            // take the center as the rotation point
            ctx.translate(canvas.width / 2, canvas.height / 2);

            centralGameSpace = centralGameArray[game].space;

            
            offset = (Math.ceil(currentIndexInCurrentCentralCircle * (360 / centralGameMatrice[centralCircleIndex].length)));

            // we do a first rotation in order to be placed in the right place to draw
            // the icon of the game on the map
            ctx.rotate(-(offset) * Math.PI / 180);
            
            /***************************************/
            // compute the sinus and cosinus of the current angle
            
            sinus = Math.sin(-(offset) * Math.PI / 180);
            cosinus = Math.cos(-(offset) * Math.PI / 180);
            oldMinX = centralCircleIndex;
            oldMinY = 0;
            oldMaxX = oldMinX + destWidth;
            oldMaxY = oldMinY + destHeight;
            newMinX = oldMinX * cosinus - oldMinY * sinus;
            newMinY = oldMinX * sinus + oldMinY * cosinus;
            newMaxX = oldMaxX * cosinus - oldMaxY * sinus;
            newMaxY = oldMaxX * sinus + oldMaxY * cosinus;
            newGameCoordinate = {
                'newMinX': newMinX + canvas.width / 2 - destWidth / 2 - 5,
                'newMinY': newMinY + canvas.height / 2 - destHeight / 2 - 5,
                'newMaxX': (newMinX + canvas.width / 2 - destWidth / 2 - 5) + destWidth + 10,
                'newMaxY': (newMinY + canvas.height / 2 - destHeight / 2 - 5) + destHeight + 10,
                'gameID': centralGameArray[game].id
            };
            gameCoordinateArray.push(newGameCoordinate);
			
            
            
            /***************************************/
            // "canceled" the translation we did before
            ctx.translate(- (canvas.width / 2), - (canvas.height / 2));
			ctx.restore(); // restore the previous context
            
            ctx.drawImage(gameImagesArray[centralGameArray[game].name], newGameCoordinate.newMinX, newGameCoordinate.newMinY, destWidth, destHeight);
			ctx.font = "8pt arial";
	        ctx.textAlign = "center";
	        ctx.fillStyle = "black";
	
			var shortened = false;
			while(ctx.measureText(centralGameArray[game].name + "...").width > 75) {
				shortened = true;
				centralGameArray[game].name = centralGameArray[game].name.substring(0, centralGameArray[game].name.length - 2);
			}
			if(shortened) {
				centralGameArray[game].name = centralGameArray[game].name + "...";
			}
	        ctx.fillText(centralGameArray[game].name, newGameCoordinate.newMinX + (destWidth / 2), newGameCoordinate.newMaxY + 3);

//            ctx.beginPath();
//            ctx.rect(centralCircleIndex + (canvas.width / 2) - (destWidth / 2), canvas.height / 2 - (destHeight / 2), destWidth, destHeight);
//            ctx.closePath();
//            ctx.stroke();
           
            ctx.fillStyle = "rgb(0,0,0)";
            ctx.beginPath();
            
//            ctx.rect(newGameCoordinate.newMinX, newGameCoordinate.newMinY, (newGameCoordinate.newMaxX - newGameCoordinate.newMinX), (newGameCoordinate.newMaxY - newGameCoordinate.newMinY));
            
            ctx.closePath();
            ctx.stroke();
            
        }
        
        centralCircleIndex = centralCircleIndexArray[Math.round(Math.random() * (centralCircleIndexArray.length - 1))];
    }
    
    
    
    // we draw the reference image on the center of the canvas
    ctx.save();
    var img = new Image();
    img.src = referenceGame.picture; 

    img.onload = function() {
        ctx.drawImage(img, canvas.width / 2 - (destWidth), canvas.height / 2 - (destHeight), destWidth * 2, destHeight * 2);
    }
	    
	    newGameCoordinate = {
	        'newMinX': canvas.width / 2 - destWidth - 5,
	        'newMinY': canvas.height / 2 - destHeight - 5,
	        'newMaxX': (canvas.width / 2 - destWidth - 5) + destWidth * 2 + 10,
	        'newMaxY': (canvas.height / 2 - destHeight - 5) + destHeight * 2 + 10,
	        'gameID': gameId
	    };
	    gameCoordinateArray.push(newGameCoordinate);
	
		ctx.font = "8pt arial";
	    ctx.textAlign = "center";
	    ctx.fillStyle = "black";

		var shortened = false;
		while(ctx.measureText(referenceGame.name + "...").width > 75) {
			shortened = true;
			referenceGame.name = referenceGame.name.substring(0, referenceGame.name.length - 2);
		}
		if(shortened) {
			referenceGame.name = referenceGame.name + "...";
		}
	    ctx.fillText(referenceGame.name, newGameCoordinate.newMinX + destWidth + 5, newGameCoordinate.newMaxY + 3);
    /*
     * we place the games on the map by turning around the center by a certain
     * amount of degrees. This amount is ajusted when two games are on the same
     * place on the map. This is stocked in the variable "offset"
     */
    var offset = 0;
    var current;
    
    var space;
    var i = 0;
    // for all the criteria
    for(var criteriaWording in similarityArray) {
        
        // for all the games we have to place...
        
        for(var game in similarityArray[criteriaWording]) {
            
            // save the context
            ctx.save();
            // take the center as the rotation point
            ctx.translate(canvas.width / 2, canvas.height / 2);
            
            // if the center place is taken by another game, we move
            // onto the other places until we found one that is
            // empty ( == null) or until we have scanned all the places for
            // this percentage and for this criteria
            
            space = similarityArray[criteriaWording][game].space;
            
//            alert(criteriaWording + ' : \n' + game);
            
            current = Math.ceil(gameMatrice[i][space].length / 2) - 1;
            var searchDownside = true;
            var searchOffset = 1;
            
            while(gameMatrice[i][space][current] != null && current >= 0 && current < gameMatrice[i][space].length) {
                if(searchDownside) {
                    // ...
                    current += searchOffset;
                    searchDownside = false;
                } else {
                    // ...
                    current -= searchOffset;
                    searchDownside = true;
                }
                searchOffset++;
            }
            
            // if we found an available place...
            if(current >= 0 && current < gameMatrice[i][space].length && gameMatrice[i][space][current] == null) {
                // we compute the offset...
                offset = (Math.ceil(gameMatrice[i][space].length / 2) - 1 - current) * (degreePerAxis / gameMatrice[i][space].length);
                // ...and then place it into the corresponding place in the game matrice (3d array repre-
                // senting the map virtually 
                gameMatrice[i][space][current] = true;
            
                // we do a first rotation in order to be placed in the right place to draw
                // the icon of the game on the map
                ctx.rotate(- ((degreePerAxis / 2) + i * degreePerAxis + offset) * Math.PI / 180);
                
                sinus = Math.sin(- ((degreePerAxis / 2) + i * degreePerAxis + offset) * Math.PI / 180);
                cosinus = Math.cos(- ((degreePerAxis / 2) + i * degreePerAxis + offset) * Math.PI / 180);
                oldMinX = 200 + ((space/percentageScale) * (canvas.width / 2));
                oldMinY = 0;
                oldMaxX = oldMinX + destWidth;
                oldMaxY = oldMinY + destHeight;
                newMinX = oldMinX * cosinus - oldMinY * sinus;
                newMinY = oldMinX * sinus + oldMinY * cosinus;
                newMaxX = oldMaxX * cosinus - oldMaxY * sinus;
                newMaxY = oldMaxX * sinus + oldMaxY * cosinus;
                newGameCoordinate = {
                    'newMinX': newMinX + canvas.width / 2 - destWidth / 2 - 5,
                    'newMinY': newMinY + canvas.height / 2 - destHeight / 2 - 5,
                    'newMaxX': (newMinX + canvas.width / 2 - destWidth / 2 - 5) + destWidth + 10,
                    'newMaxY': (newMinY + canvas.height / 2 - destHeight / 2 - 5) + destHeight + 10,
                    'gameID': similarityArray[criteriaWording][game].id
                };
                gameCoordinateArray.push(newGameCoordinate);
                
                // "canceled" the translation we did before
                ctx.translate(- (canvas.width / 2), - (canvas.height / 2));

                // we move the rotation point to the center of the icon of the current game
                //ctx.translate((canvas.width / 2) + ((similarityArray[i].criteria[criteriaArray[j]]/percentageScale) * (canvas.width / 2)) - (destWidth / 2), canvas.height / 2 - (destHeight / 2));
                // we rotate by the inverse value given as an argument of the first rotation in order to
                // placed the icon on an horizontal axis
                //ctx.rotate(((degreePerAxis / 2) + j * degreePerAxis + offset) * Math.PI / 180);
                // "canceled" the translation we did before
                //ctx.translate(-((canvas.width / 2) + ((similarityArray[i].criteria[criteriaArray[j]]/percentageScale) * (canvas.width / 2)) - (destWidth / 2)), - (canvas.height / 2 - (destHeight / 2)));
                // we draw the image now we are placed, by moving by half of the image width and height
                // the actual position in order to the icon to be centered around that point
                
                	ctx.restore();
					ctx.restore();
                    ctx.drawImage(gameImagesArray[game], newGameCoordinate.newMinX, newGameCoordinate.newMinY, destWidth, destHeight)
					ctx.font = "8pt arial";
			        ctx.textAlign = "center";
			        ctx.fillStyle = "black";
			
					var shortened = false;
					while(ctx.measureText(game + "...").width > 75) {
						shortened = true;
						game = game.substring(0, game.length - 2);
					}
					if(shortened) {
						game = game + "...";
					}
			        ctx.fillText(game, newGameCoordinate.newMinX + (destWidth / 2), newGameCoordinate.newMaxY + 3);
               	
                    // ctx.strokeStyle = "rgb(204,204,204)";
                    // ctx.beginPath();
                    // 
                    // ctx.rect(newGameCoordinate.newMinX, newGameCoordinate.newMinY, (newGameCoordinate.newMaxX - newGameCoordinate.newMinX), (newGameCoordinate.newMaxY - newGameCoordinate.newMinY));
                    // 
                    // ctx.closePath();
                    // ctx.stroke();
                        /*
                    ctx.beginPath();
                    ctx.arc(canvas.width / 2, canvas.height / 2, (space/percentageScale) * (canvas.width / 2), 0, Math.PI*2, true); 
                    ctx.closePath();
                ctx.stroke();*/
                
            }
        }
        i++;
    }
}
// we create the 3d array that represente the map (virtually)
var gameMatrice;
var circleArray;
function initGameMatrice() {
	
	// we create the 3d array that represente the map (virtually)
	gameMatrice = new Array();

	// the different gaps
	var percentageArray = [2, 5, 10];
	// number of circle for each gap
	var circlePerPercentageCountArray = [6, 6, 3];
	// number of circle traced for the current gap
	var currentCirclePerPercentageCount = 0;
	// current percentage per traced circle. This is an index
	// which point at the current gap in percentageArray
	var currentPercentagePerCircleIndex = 0;

	var gameCountPerCircle = 5;

	circleArray = new Array();

	// 4 axis...
	for(var n = 0 ; n < 4 ; n++) {
	    gameMatrice[n] = new Array();
	    // from 0 to (percentageScale) % with a step depending on the current gap

	    for(var l = 0 ; l <= percentageScale ; l = l + percentageArray[currentPercentagePerCircleIndex]) {
	        gameMatrice[n][l] = new Array();
	        // the maximum number of games that can be placed on the same circle
	        // is dynamicaly increased from circle to circle

	        for(var m = 0 ; m < gameCountPerCircle ; m++) {
	            gameMatrice[n][l][m] = null;
	        }

	        // if we have enough circle traced for the current gap...
	        if(currentCirclePerPercentageCount == circlePerPercentageCountArray[currentPercentagePerCircleIndex] - 1) {
	            // if we have crossed all the gaps we exit the loop
	            if(currentPercentagePerCircleIndex == percentageArray.length - 1) {
	                break;
	            } else { // ...elsewere, we reset the number of circle traced for the current gap
	                // and we change the current gap
	                currentCirclePerPercentageCount = 0;
	                currentPercentagePerCircleIndex++;
	            }
	        } else { // else, we increase the number of traced circle for the current gap
	            currentCirclePerPercentageCount++;
	        }

	        gameCountPerCircle += percentageArray[currentPercentagePerCircleIndex] / 2;
	        if(n == 0) {
	            circleArray.push(l);
	        }
	    }
	    currentCirclePerPercentageCount = 0;
	    currentPercentagePerCircleIndex = 0;
	    gameCountPerCircle = 5;

	}
}
initGameMatrice();
function sortGamesByCircle(gameArray) {
    var i;
    for(var criteria in gameArray) {
        criteria = gameArray[criteria];
        for(var game in criteria) {
            game = criteria[game];
            for(i = 0 ; i < circleArray.length ; i++) {
                
                if(circleArray[i] >= game.space) {
                    
                    if(i > 0) {
                        if(circleArray[i] - game.space < game.space - circleArray[i - 1]) {
                            game.space = circleArray[i];
                        } else {
                            game.space = circleArray[i - 1];
                        }
                        break;
                    }
                }
            }
        }
    }
}

// PxLoader is a plugin that allow us to preload files, like
// images in our case
function initMapData() {
	var loader = new PxLoader();
	var gameImagesArray = new Array()
	var gameId = $("input[name=game_id]").val();
	
	var search_url = $("input[name=search_url]").val();
	
	$.ajax({
	    url: search_url+'/'+gameId,
	    type: "GET"
	}).done(function(array) {

	    similarityArray = array.games_petal;
	    gamePicturesArray = array.pictures;
	    referenceGame = array.game_ref;
	    centralGameArray = array.games_central;

	    // we preload icon of each game we have to place...
	    for(var picture in gamePicturesArray) {
	        // $.ajax({
	        //             url: addDropShadowUrl+'?filename='+gamePicturesArray[picture],
	        //             type: "GET",
	        //             async: false,
	        //             timeout: 5000
	        //         }).done(function(new_filename) {
	        //             if(new_filename != 'Error') {
	                // gameImagesArray[picture] = loader.addImage(new_filename);
	            // } else {
	                gameImagesArray[picture] = loader.addImage(gamePicturesArray[picture]);
	            // }
	        // });
	    }

	    // callback that will be run once images are ready 
	    loader.addCompletionListener(function() {

	        var gameArray = new Array();
	        var gameCriteriaArray;
	        var game;

	        $.each(similarityArray, function(key, value) {
	            gameCriteriaArray = new Array();
	            $.each(value, function(key, value) {
	                game = new Array();
	                $.each(value, function(key, value) {
	                    game[key] = value;
	                    game.length++;
	                })
	                gameCriteriaArray[key] = game;
	                gameCriteriaArray.length++;
	            })
	            gameArray[key] = gameCriteriaArray;
	            gameArray.length++;
	        });

	        sortGamesByCircle(gameArray);
	        console.dir(gameImagesArray);
		
	        draw(4, gameImagesArray, gameArray, gameMatrice);
	    }); 

	    // begin downloading images 
	    loader.start();
	})
}

initMapData();